import $store from '@/store/index.js';
export default {
	/* 获取成员列表 */
	getGroupMembersList(group_id) {
		return $store.state.user.sqlite.groupMembers.where({ field: 'group_id', val: `'${group_id}'` }).get()
	},
	//更新或添加成员列表 
	async addOrEditGroupMembers(data) {
		//逻辑是先插入如果插入失败，就更新
		try{
			await $store.state.user.sqlite.groupMembers.create(data)
			return true
		}catch(e){
			try{
				await this.editGroupMembers(data.group_id,data.user_id,data)
				return true
			}catch(e){
				console.log(e);
				throw e
			}
		}
	},
	
	/* 新增或替换成员列表  */
	replaceGroupMembers(data){
		return $store.state.user.sqlite.groupMembers.replace(data)
	},
	//批量插入或替换群成员
	batchReplaceMembers(data){
		return $store.state.user.sqlite.groupMembers.batchReplace(data)
	},
	
	//更新群成员
	editGroupMembers(group_id,user_id,data) {
		return $store.state.user.sqlite.groupMembers.where([{
			field: 'group_id',
			val: `${group_id}`,
			logic: 'AND'
		},{
			field: 'user_id',
			val: `'${user_id}'`,
			logic: 'AND'
		}]).update(data)
	},
	//更新群成员资料
	editGroupMembersInfo(user_id,data) {
		return $store.state.user.sqlite.groupMembers.where({ field: 'user_id', val: `'${user_id}'`}).update(data)
	},
	//更新这个群的所有其他字段
	editGroupMembersAll(group_id,data) {
		return $store.state.user.sqlite.groupMembers.where({
			field: 'group_id',
			val: `${group_id}`,
			logic: 'AND'
		}).update(data)
	},
	
	//批量更新同一个操作
	batchEditGroupMembers(group_id,user_ids,data) {
		let userIds = user_ids.map(v => `'${v}'`).join(',')
		return $store.state.user.sqlite.groupMembers.where([{
			field: 'group_id',
			val: `${group_id}`,
			logic: 'AND'
		},{
			field: 'user_id',
			val: `(${userIds})`,
			logic: 'AND',
			opt: "in"
		}]).update(data)
	},
	
	//删除群所有的群成员
	delGroupMembersAll(group_id) {
		return $store.state.user.sqlite.groupMembers.where({ field: 'group_id', val: `'${group_id}'`}).delete()
	},
	
	//删除群单个群成员
	delGroupMembers(group_id,user_id) {
		return $store.state.user.sqlite.groupMembers.where([{
			field: 'group_id',
			val: `${group_id}`,
			logic: 'AND'
		},{
			field: 'user_id',
			val: `'${user_id}'`,
			logic: 'AND'
		}]).delete()
	},
	//删除群多个群成员
	batchDelGroupMembers(group_id,user_ids) {
		let userIds = user_ids.map(v => `'${v}'`).join(',')
		return $store.state.user.sqlite.groupMembers.where([{
			field: 'group_id',
			val: `${group_id}`,
			logic: 'AND'
		},{
			field: 'user_id',
			val: `(${userIds})`,
			logic: 'AND',
			opt: "in"
		}]).delete()
	},
}